package com.cb.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 加密工具类
 * @author sdm
 *
 */
public class EncryptUtil {
	private final static Log log=LogFactory.getLog(EncryptUtil.class);
	/**
	 * hmac-md5 加密算法的缺省实现
	 * @param crackText 要加密的内容
	 * @param key 双方的私钥
	 * @return 加密后的数字指纹
	 */
	public static String hmacMd5Transalte(String crackText,String key) {
		String result="";
		try
		{
			byte[] plainText = crackText.getBytes("UTF8");
			byte[] keyBytes=key.getBytes("UTF8");
			 
		    SecretKey MD5key = new SecretKeySpec(keyBytes, "HmacMD5"); 
	
		    Mac mac = Mac.getInstance("HmacMD5");
		   
		    mac.init(MD5key);
	
		    mac.update(plainText);
		    	    
		   byte[]re= mac.doFinal();
		  
		   for(int i=0;i<re.length;i++){ 
		   	result += Integer.toHexString((0x000000ff&re[i])|0xffffff00).substring(6); 
		   }
		}
		catch(Exception ex){
			if(log.isDebugEnabled()){
				log.debug("hmacMd5Transalte" + ex.getMessage());
			}
		}
		return result;
	}

	/**
	 * md5 crack
	 * @param text
	 */
	public static String md5Translate(String text) {
		
		MessageDigest msgDigest = null;

        try {
            msgDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("System doesn't support MD5 algorithm.");
        }

        msgDigest.update(text.getBytes());

        byte[] bytes = msgDigest.digest();

        byte   tb;
        char   low;
        char   high;
        char   tmpChar;

        String md5Str = new String();

        for (int i = 0; i < bytes.length; i++) {
            tb = bytes[i];

            tmpChar = (char) ((tb >>> 4) & 0x000f);

            if (tmpChar >= 10) {
                high = (char) (('a' + tmpChar) - 10);
            } else {
                high = (char) ('0' + tmpChar);
            }

            md5Str += high;
            tmpChar = (char) (tb & 0x000f);

            if (tmpChar >= 10) {
                low = (char) (('a' + tmpChar) - 10);
            } else {
                low = (char) ('0' + tmpChar);
            }

            md5Str += low;
        }

        return md5Str;
	}
}
